﻿using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RotovapPlatform.UI.ViewModels.ExperimentManagement;

namespace RotovapPlatform.UI.Views.ExperimentManagement
{
	/// <summary>
	/// MainOperationView.xaml 的交互逻辑
	/// </summary>
	public partial class MainOperationView : UserControl
	{
		private readonly ILogger<MainOperationView> _logger;
		private readonly MainOperationViewModel _viewModel;

		public MainOperationView()
		{
			InitializeComponent();

			try
			{
				// 获取日志服务
				_logger = App.ServiceProvider.GetRequiredService<ILogger<MainOperationView>>();

				// 获取ViewModel并设置为DataContext
				_viewModel = App.ServiceProvider.GetRequiredService<MainOperationViewModel>();
				DataContext = _viewModel;

				// 注册Loaded事件，在视图加载时启动设备状态更新
				Loaded += MainOperationView_Loaded;

				// 注册Unloaded事件，在视图卸载时释放资源
				Unloaded += MainOperationView_Unloaded;
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "MainOperationView初始化失败");
			}
		}

		private async void MainOperationView_Loaded(object sender, RoutedEventArgs e)
		{
			try
			{
				_logger?.LogInformation("MainOperationView页面已加载，开始初始化和订阅设备状态");

				// 初始化ViewModel并启动设备状态更新
				await _viewModel.InitializeAsync();

				// 启动设备状态监控
				//_viewModel.StartDeviceStatusMonitoring();
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "MainOperationView加载异常");
			}
		}

		private void MainOperationView_Unloaded(object sender, RoutedEventArgs e)
		{
			try
			{
				_logger?.LogInformation("MainOperationView页面已卸载，正在停止设备状态监控");

				// 停止设备状态监控
				_viewModel.StopDeviceStatusMonitoring();
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "MainOperationView卸载异常");
			}
		}
	}
}